package com.gz.spring.aop.proxy2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class OperProxyProvider {
    private Operation target_operation;

    public OperProxyProvider(Operation operation) {
        this.target_operation = operation;
    }

    public Operation getProxy() {
        ClassLoader classLoader = this.target_operation.getClass().getClassLoader();
        Class<?>[] interfaces = this.target_operation.getClass().getInterfaces();

        InvocationHandler invocationHandler = new InvocationHandler() {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                //这里扩展一下Arrays.toString(args)换成Arrays.asList(args)也行
                //Arrays.asList(args)是固定大小的List，即不能add、remove
                //如果需要增添或删除，需要转为ArrayList
                Object result = null;
                try {
                    result = method.invoke(target_operation, args);
                    System.out.println("方法内部打印result=" + result);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    System.out.println("方法执行开始-日志-方法名-" + method.getName()+
                            "-异常类型="+e.getClass().getName());
                }  finally {
                    System.out.println("方案最终结束-日志-方法名-"+method.getName());
                }
                System.out.println("=================================");
                return result;
            }
        };

        Operation operation = (Operation) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
        return operation;
    }
}
